Ext.onReady(function(){
	Ext.create("Ext.panel.Panel", {
		renderTo: Ext.getBody(),
		items: [signedDetail(), signedReceivePanel()]
	});
	
	//本次应收认购总金额
    var canReceiveMoney = 0;
	//加载认购信息
    signedDetail.getForm().load({
	    url: 'getSignedById',
	    params: {"id": relationId},
	    success: function(form, action){
	    	//总认购金额
	    	var info_receivable = action.result.data.info_receivable;
	    	//已收认购金额
	    	var info_received = action.result.data.info_received;
	    	//收款表单,设置收款最大值
	    	canReceiveMoney = info_receivable - info_received;
	    	signedReceivePanel.getForm().findField("realAmount").setMaxValue(canReceiveMoney);
	    	signedReceivePanel.getForm().findField("realAmount").setValue(canReceiveMoney);
	    	
	    	//收款信息,添加结算人员
	    	signedReceivePanel.getForm().findField("userName").setValue(action.result.data.userName);
	    	signedReceivePanel.getForm().findField("userId").setValue(action.result.data.userId);
	    	signedReceivePanel.getForm().findField("userCode").setValue(action.result.data.userCode);
	    	signedReceivePanel.getForm().findField("relationId").setValue(relationId);
	    	
	    	//合同金额大写
	    	signedDetail.getForm().findField("info_signAmount_cn").setValue("");
	    	signedDetail.getForm().findField("info_signAmount_cn").setValue("<font style=\"font-size: 25px; color: red;\">" + action.result.data.info_signAmount_cn + "</font>");
	    	//已收金额
	    	signedDetail.getForm().findField("info_received").setValue("");
	    	signedDetail.getForm().findField("info_received").setValue("<font style=\"color: red;\">" + Ext.util.Format.number(action.result.data.info_received, "0,000.00") + "</font>");
	    	//未收定金
	    	signedDetail.getForm().findField("info_unReceived").setValue("");
	    	signedDetail.getForm().findField("info_unReceived").setValue("<font style=\"color: red;\">" + Ext.util.Format.number(action.result.data.info_unReceived, "0,000.00") + "</font>");

            signedReceivePanel.getForm().findField("payerName").setValue(action.result.data.customerName);
    	},
	    failure: function(form, action) {
	        Ext.Msg.alert("加载失败", action.result.errorMessage);
	    }
	});
});

function signedDetail(){
	return signedDetail = Ext.create("Ext.form.Panel", {
		title: "签约信息",
        layout: "fit",
        items: {
            xtype: "form",
            bodyPadding:10,
            layout: "form",
            fieldDefaults: {
                labelWidth: 120,
                labelAlign: "right",
                margin: "0 0 10 0"
            },
            items: [
            	{
            	xtype: "fieldcontainer",
            	layout: "hbox",
                items: [
                	{xtype: "fieldcontainer", layout: "column",
	    				items:[
	    				{xtype: "displayfield",name: "info_signCode",fieldLabel: "签约编号"},
	    				{xtype: "displayfield",name: "",fieldLabel: "签约", value: "<font style=\"font-weight: 700\">签约</font>"}
	    				]
    				}
                ]},
                {
                xtype: "fieldcontainer",
                layout: "hbox",
                items: [
                	{xtype: "fieldcontainer", layout: "column",
	    				items:[
	    				{xtype: "displayfield",name: "info_signPrice",fieldLabel: "签约单价", renderer: Ext.util.Format.numberRenderer('0,000.00')},
	    				{xtype: "displayfield", value: "元"}
	    				]
    				},
    				{xtype: "fieldcontainer", layout: "column",
	    				items:[
	    				{xtype: "displayfield",name: "info_signAmount",fieldLabel: "合同金额", renderer: Ext.util.Format.numberRenderer('0,000')},
	    				{xtype: "displayfield", value: "元"},
	    				{xtype: "displayfield", value: "(取整)"}
	    				]
    				}
                ]},
            	{xtype: 'displayfield', name: "info_signAmount_cn", fieldLabel: '合同金额大写'},
        		{
                xtype: "fieldcontainer",
                layout: "hbox",
                items: [
                	{xtype: "fieldcontainer", layout: "column",
	    				items:[
	    				{xtype: "displayfield", name: "info_placeholder", fieldLabel: "已收定金"},
	    				{xtype: "displayfield",name: "info_depReceived",fieldLabel: "认筹金", renderer: Ext.util.Format.numberRenderer('0,000.00')},
	    				{xtype: "displayfield", value: "元"},
	    				{xtype: "displayfield", value: ","},
    					{xtype: "displayfield",name: "info_subReceived",fieldLabel: "认购金", renderer: Ext.util.Format.numberRenderer('0,000.00')},
	    				{xtype: "displayfield", value: "元"},
	    				{xtype: "displayfield", value: ","},
    					{xtype: "displayfield",name: "info_dep_sub_received",fieldLabel: "共计", renderer: Ext.util.Format.numberRenderer('0,000.00')},
    					{xtype: "displayfield", value: "元"}
	    				]
    				}
                ]},
    			//{xtype: "displayfield", name: "info_paymentMethod",fieldLabel: "付款方式"},
    			{
                    xtype: "fieldcontainer",
                    layout: "hbox",
                    items: [
                    	{xtype: "displayfield",name: "info_paymentMethod",fieldLabel: "合同金付款方式"},
    	    			{xtype: "displayfield",name: "info_decorationPaymentMethod",fieldLabel: "首付分期付款方式"}
                    ]
    			},
    			{xtype: "fieldcontainer", items: [needReceiveRefundGrid()]},
				{
                xtype: "fieldcontainer",
                layout: "hbox",
                items: [
                	{xtype: "fieldcontainer", layout: "column",
	    				items:[
	    				{xtype: "displayfield",name: "info_received",fieldLabel: "已收金额"},
	    				{xtype: "displayfield", value: "元"}
	    				]
    				},
    				{xtype: "fieldcontainer", layout: "column",
	    				items:[
	    				{xtype: "displayfield",name: "info_unReceived",fieldLabel: "未收金额"},
	    				{xtype: "displayfield", value: "元"}
	    				]
    				}
                ]}
            ]
		}
	});
}

function needReceiveRefundGrid(){
	var columns = [
		{text: '款项', dataIndex: 'receivablesFunds'},
        {text: '应收金额', dataIndex: 'totalReceivablesAmount'},
        {
        text: '应收日期',
    	dataIndex: 'receivablesDate',
    	format: 'Y-m-d',
    	renderer : function(val) {
			if(val!=null&&val!=""){
				return Ext.Date.format(new Date(val), "Y-m-d");
			}
			return null;
		}},
        {text: '银行/单位', dataIndex: 'orgName'},
        {text: '经办人', dataIndex: 'agentName'},
        {text: '已收金额', dataIndex: 'haveReceivedTotal'},
        {text: '未收金额', dataIndex: 'unReceivedTotal'}
	];
	
	//加载签约待收款记录
    var signedReceiveStore = Ext.create('Ext.data.Store', {
        fields: ["receivablesFunds","totalReceivablesAmount","receivablesDate", "orgName", "agentName","haveReceivedTotal","unReceivedTotal"],
        pageSize: 10,  //页容量5条数据
        //是否在服务端排序 （true的话，在客户端就不能排序）
        remoteSort: false,
        proxy: {
            type: 'ajax',
            url: jypath+'/marketing/proceeds/needList?relationId='+relationId+"&docType=0&businessType=2",
            reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
                type: 'json', //返回数据类型为json格式
                root: 'rows',  //数据
                totalProperty: 'total' //数据总条数
            }
        },
        autoLoad: true  //即时加载数据
    });
	
	return needReceiveRefundGrid = Ext.create('Ext.grid.Panel', {
	    store: signedReceiveStore,
	    columns: columns,
	    width: 700
	});
}

function signedReceivePanel(){
	//结算方式
	/*var statementTypeList = [
         {"value":"1","text":"现金"},
         {"value":"2","text":"支票"},
         {"value":"3","text":"汇票"},
         {"value":"4","text":"转账"},
         {"value":"5","text":"POS转账"},
         {"value":"6","text":"支付宝"},
         {"value":"7","text":"银联"},
         {"value":"8","text":"银行转入"},
         {"value":"9","text":"银行按揭"}
     ];*/
    var statementTypeList = [
        {"value":"1","text":"现金"},
        {"value":"4","text":"转账"},
        {"value":"5","text":"POS机"},
        {"value":"10","text":"折扣"}
    ];
	var statementTypeStore = Ext.data.Store({
    	autoDestroy: true,
        fields :["value","text"],
        data : statementTypeList
    });

    //入账银行
    var bankList = [
        {"value":"1","text":"华融湘江银行株洲芦淞支行预售资金监管户"},
        {"value":"2","text":"建设银行株洲人民路支行"},
        {"value":"3","text":"建设银行株洲人民路支行0165"},
        {"value":"4","text":"浦发银行监管户"},
        {"value":"5","text":"浦发银行株洲长江路支行"},
        {"value":"6","text":"浦发银行株洲长江路支行0409"},
        {"value":"7","text":"浦发银行株洲长江路支行保证金户"},
        {"value":"8","text":"兴业银行株洲石峰支行"},
        {"value":"9","text":"招商银行株洲支行"},
        {"value":"10","text":"招商银行株洲支行预售资金监管专户"},
        {"value":"11","text":"中国工商银行株洲高新技术开发支行"},
        {"value":"12","text":"中国建设银行株洲电力支行预售资金监管户"},
        {"value":"13","text":"中国银行株洲清水塘支行"},
        {"value":"14","text":"中信银行株洲建设路支行"},
        {"value":"15","text":"华融湘江银行株洲芦淞支行"}
    ];
    var bankStore = Ext.data.Store({
        autoDestroy: true,
        fields :["value","text"],
        data : bankList
    });

    var needReceiveRefundStore = new Ext.data.Store({
    	fields:['id','receivablesFunds'],
    	autoLoad: true,
    	singleton:true,
        autoDestroy:true,
	    proxy: {
	        type: 'ajax',
	        url: jypath+'/marketing/proceeds/needDropDownList?relationId='+relationId,
	        reader: {
	            type: 'json',
	            root: 'root'
	        }
	    }
	});

	var cbstore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["projectName", "id"],
	        proxy:{
	            type:'ajax',
	            url:jypath+'/estate/project/findProjectList',
	            reader:{
                    type: 'json', 
                    root: 'root'  //数据
               }
	        },
	        autoLoad:true
    });
   
	//上传图片展示框
	var showImgPanel = Ext.create('Ext.Panel', {
        width:600,
       	height:120,
        frame: true,
        collapsible: false,
      	autoScroll:true,
      	bodyStyle: 'overflow-y:hidden; overflow-x:auto',
        layout: "hbox"
    });
	
	//收款附件表单
	var ajaxFileUploadForm = Ext.create("Ext.form.Panel", {
		border: false,
		items: [{
            xtype: 'filefield',
            fieldLabel: "上传凭证",
            buttonText: "上传凭证",
            name: "file",
            layout: "hbox",
            validator: function(value){
            	if(value){
            		if(!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG|BMP)$/.test(value)){
			      		return "图片格式不正确!";
				    }else{
				    	return true;
				    }
            	}else{
			    	return true;
			    }
			},
            listeners: {
        		change: function(file){
        			var form = ajaxFileUploadForm.getForm();
	                if(form.isValid()){
		                form.submit({
		                    url: jypath + '/common/file/extUploadFile?type=1',
		                    waitMsg: '附件上传中,请稍候...',
		                    success: function(form, action) {
		                    	var fileName = action.result.fileName;
		                    	var httpUrl = action.result.url;
		                    	var imgs="<a href='"+httpUrl+"' target='_blank'><img style='width: 80px; height: 90px;' title='"+fileName+"' src='"+httpUrl+"'/></a>";
		                    	var imgPanel = Ext.create("Ext.Panel", {
							        html: imgs
		                    	})
								showImgPanel.add(imgPanel);
								//添加隐藏字符串
								var fileArr = signedReceivePanel.getForm().findField("fileArr").getValue();
								if(!fileArr){
									fileArr = httpUrl;
								}else{
									fileArr = fileArr + "|" + httpUrl;
								}
								signedReceivePanel.getForm().findField("fileArr").setValue(fileArr);
								Ext.getCmp("certification").show();
			       			},
			       			failure: function(form, action){
	                        	Ext.Msg.alert('Failure', 'Your photo "' + action.result.fileName + '" has been uploaded.');
			       			}
		                });
	                }
        		}
        	}
        },{
        	xtype: "fieldcontainer",
        	layout: "hbox",
        	fieldLabel: "凭证附件",
        	id: "certification",
        	name: "certification",
        	hidden: true,
        	items: [showImgPanel]
        }]
	});
	
	return signedReceivePanel = Ext.create("Ext.form.FormPanel", {
        title: "收款信息",
        layout: "fit",
        margin: "10 0 0 0",
        items: {
            xtype: "form",
            bodyPadding:5,
            border: false,
            layout: "form",
            fieldDefaults: {
                labelWidth: 80,
                labelAlign: "right",
                margin: "0 0 10 0"
            },
            items: [{
                	xtype : 'textfield', fieldLabel : '结算人员ID',
			    	name: "userId", readOnly: true, hidden: true
                },{
                	xtype : 'textfield', fieldLabel : '结算人员Code',
			    	name: "userCode", readOnly: true, hidden: true
                },{
                	xtype : 'textfield', fieldLabel : '认购编号Id',
			    	name: "relationId", readOnly: true, hidden: true
                },{
                	xtype : 'textfield', fieldLabel : '收款类型',
			    	name: "businessType", readOnly: true, hidden: true,
			    	value: 2
                },{
                	xtype : 'textfield', fieldLabel : '收款凭证',
			    	name: "fileArr", readOnly: true, hidden: true
				},{
             		xtype: "fieldcontainer",
                	layout: "hbox",
                	items: [{
	                	xtype : 'combobox',
		                layout: "hbox",
		                name: "needReceiveId",
						fieldLabel : '应收款项',
				    	valueField: "id",
				    	displayField: "receivablesFunds",
						store: needReceiveRefundStore,
				    	blankText: "应收款项不能为空!",
				    	allowBlank: false,
				    	editable: false,
				    	listeners: {
					    	select: function(combo,record, index){
					    		//1、选中支付的款项
					    		//2、获取未收金额,并添加为收款的最大值
				    			var comboId = combo.getValue();
				    			var rec = needReceiveRefundGrid.getStore().getAt(0);
				    			var needStores = needReceiveRefundGrid.getStore();
				    			for(var i=0; i<needStores.getCount(); i++){  
				                    var record = needStores.getAt(i);
				                    var recordId = record.get("id");
				                    if(recordId == comboId){
				                    	var unReceivedTotal = record.get("unReceivedTotal");
				                    	var needToReceive = record.get("totalReceivablesAmount");
				                    	signedReceivePanel.getForm().findField("realAmount").setMaxValue(unReceivedTotal);
										signedReceivePanel.getForm().findField("realAmount").setValue(unReceivedTotal);
				                    }
				                }
				    		}
				    	}
	            	}]
	            },{
                xtype: "fieldcontainer",
                layout: "hbox",
                items: [{
                	xtype: "numberfield",
                	fieldLabel: "收款金额",
                	name: "realAmount",
		            layout: "hbox",
                	allowBlank:false,
                	hideTrigger:true,
                	blankText: "收款金额不能为空!",
                	minValue: 1,
                	listeners: {
                		change: function(field){
                			var totalRecField = signedReceivePanel.getForm().findField("totalRec")
                			totalRecField.setValue("<font style='color: red; font-size: 30px;'>"+Ext.util.Format.number(field.getValue(), "0,000.00") +"元</font>");
                		}
                	}
            	},
                {
                	xtype: "displayfield",
                	name: "totalRec",
                	fieldLabel: "本次收款总额"
            	}]
          	},
			{
                    xtype : 'container',
                    layout : 'hbox',
                    items : [{
                        xtype: "radiogroup",
                        fieldLabel: "收据类型",
                        width: 320,
                        items: [{
                            boxLabel: '电子票据',
                            inputValue: '1',
                            id: 'radio1',
                            name: "billType",
							checked: true,
                            listeners: {
                                'change': function (value) {
                                    Ext.getCmp('billCode').setDisabled(false);
                                    Ext.getCmp('billCode').show();
                                }
                            }
                        }, {
                            boxLabel: '纸质票据',
                            inputValue: '2',
                            id: 'radio2',
                            name: "billType",
                            listeners: {
                                'change': function (value) {
                                    Ext.getCmp('billCode').setDisabled(true);
                                    Ext.getCmp('billCode').hide();
                                }
                            }
                        }]
                    }]
			},
         	{
	        	xtype: "fieldcontainer",
	            layout: "hbox",
	            items: [{
	                xtype: "textfield",
	        		fieldLabel: "票据号码",
	        		name: "billCode",
                    id: "billCode",
					hidden: true,
					disabled: true,
	        		maxLength: 100,
	        		width:475
	            }]
        	},
        	{
				xtype: "fieldcontainer",
	            layout: "hbox",
	            items: [{
	                xtype : 'combobox',
					fieldLabel : '结算方式',
					store: statementTypeStore,
			    	displayField: "text",
			    	valueField: "value",
			    /*	allowBlank: false,
			    	blankText: "结算方式不能为空!",*/
			    	id: "statementType",
			    	name: "statementType",
			    	editable: false,
			    	listeners: {
			    		select: function(combo,record, index){
			    			//当选中数据为 POS转账 时,隐藏/显示转账手续费字段
			    			//动态控制手续费字段是否可以为空
			    			var value = combo.getValue();
		    				var serviceFeeField = signedReceivePanel.getForm().findField("serviceFee");
			    			if(value == 5){
	                    		serviceFeeField.show();
	                    		//serviceFeeField.allowBlank=false;
	                    		//serviceFeeField.blankText="POS转账,手续费不能为空";
			    			}else{
			    				serviceFeeField.setValue(null);
			    				serviceFeeField.allowBlank=true;
	                    		serviceFeeField.blankText="";
			    				serviceFeeField.hide();
			    			}
			    		}
			    	}
	            },
				{
                	xtype: "numberfield",
                	fieldLabel: "转账手续费",
                	name: "serviceFee",
                	hidden: true,
                	hideTrigger:true,
                	minValue: 0
            	}]
        	},
			{
                xtype: "fieldcontainer",
                layout: "hbox",
                items: [{
                    xtype: "fieldcontainer",
                    layout: "hbox",
                    items: [{
                        xtype: "textfield",
                        fieldLabel: "交款人",
                        name: "payerName",
                        id: "payerName",
                        maxLength: 100
                    }]
                }]
			},
			{
        		xtype: "fieldcontainer",
                layout: "hbox",
                items: [{
                	xtype : 'textfield',
					fieldLabel : '结算人员',
			    	name: "userName",
			    	readOnly: true
                },{
                	xtype : 'datefield',
                	name: "statementDate",
					fieldLabel : '结算日期',
					format: 'Y-m-d',
					value: new Date(),
					maxValue: new Date()
                }]
        	},
			{
                xtype: "fieldcontainer",
                layout: "hbox",
                items: [{
                    xtype : 'combobox',
                    fieldLabel : '入账银行',
                    store: bankStore,
                    displayField: "text",
                    valueField: "value",
                    id: "bankCode",
                    name: "bankCode",
                    editable: false
                }]
			},
			{
                xtype: "fieldcontainer",
	            layout: "hbox",
	            items: [{
	                xtype: "textarea",
	                name: "remark",
	        		height: 100,
	                fieldLabel: "备注",
	                width:475
	            }]
        	},{
        		xtype: "fieldcontainer",
	            layout: "hbox",
	            items: [{
	        		xtype: "fieldcontainer",
		            layout: "hbox",
		            items: [ajaxFileUploadForm]
	        	}]
        	}],
        	buttonAlign: "left",
        	buttons: [{
                text:'保存',
                handler: function(){
		        	var form = signedReceivePanel.getForm();
				    if(form.isValid()){
				    	// 发送请求
				    	var waiting = Ext.Msg.wait('正在处理，请稍等...','','');
						Ext.Ajax.request({
							method: "POST",
							url: "proceeds",
							params: form.getValues(),
							success: function(response, options){
								if(waiting != null){
									waiting.hide();
								}
								var jsonResult = Ext.decode(response.responseText);
								if(jsonResult.success==true){
									 Ext.MessageBox.alert("系统提示", "保存成功! ", function(but) {  
										 var tabKey = "sig_pay"+relationId;
						                 parent.TabControlRemove(tabKey);
    				                }); 
								}else{
									Ext.Msg.alert('失败', jsonResult.errorMessage);
								}
							},
							failure: function(response, options){
								Ext.Msg.alert('错误', '请求超时.');
							}
						});
					}
            	}
            },{
                text: '返回',
                handler: function(){
                	var tabKey = "sig_pay"+relationId;
                	parent.TabControlRemove(tabKey);
     			}
            }]
        }
    });
}